package net.gazhi.delonix.grac.service;

import java.util.List;

import net.gazhi.delonix.core.dao.PageInfo;
import net.gazhi.delonix.core.entity.LoginUser;
import net.gazhi.delonix.core.service.AbstractEntityService;
import net.gazhi.delonix.core.thread.ThreadContext;
import net.gazhi.delonix.grac.AC_TB;
import net.gazhi.delonix.grac.entity.gru.User;
import net.gazhi.delonix.grac.entity.gru.UserDir;
import net.gazhi.delonix.grac.form.UserSearchForm;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
@Transactional(readOnly = true)
public class UserService extends AbstractEntityService<User> {

	@Autowired
	private UserDirService userDirService;

	/**
	 * 根据用户名查找用户
	 * 
	 * @param loginName
	 * @return
	 */
	public User findByLoginName(String loginName) {
		return (User) super.createCriteria().add(Restrictions.eq("loginName", loginName)).setMaxResults(1).uniqueResult();
	}

	/**
	 * 修改用户语言
	 * 
	 * @param locale
	 */
	@Transactional
	public void switchLocale(String locale) {
		LoginUser user = ThreadContext.getLoginUser();
		if (user.getId() <= 0) {
			return;
		}
		user.setLocale(locale);
		dao.createSQLQuery("update " + AC_TB.ac_user + " set locale=? where id=?").setParameter(0, locale).setParameter(1, user.getId()).executeUpdate();
	}

	@SuppressWarnings("unchecked")
	public List<User> search(UserSearchForm form, PageInfo pageInfo) {
		Criteria query = super.createCriteria("u").createAlias("u.userDir", "d");
		if (StringUtils.hasLength(form.getKeyword())) {
			String param = "%" + form.getKeyword() + "%";
			query.add(Restrictions.or(Restrictions.like("u.nameZh", param), Restrictions.like("u.nameEn", param)));
		}
		if (form.isListSubdir()) {
			UserDir dir = this.userDirService.get(form.getDirId());
			query.add(Restrictions.ge("d.fullId", dir.getFullId()));
			query.add(Restrictions.le("d.fullId", dir.getFullId() + "~"));
		} else {
			query.add(Restrictions.eq("d.id", form.getDirId()));
		}
		return (List<User>) dao.listPage(query, pageInfo, Order.asc("u.isDisabled"), Order.asc("showOrder"));
	}
}
